//
//  LeaderPersonalInforVC.m
//  SelfDrivingTravelling-IOS
//
//  Created by Teplot_01 on 16/9/1.
//  Copyright © 2016年 Teplot_01. All rights reserved.
//

#import "LeaderPersonalInforVC.h"

@interface LeaderPersonalInforVC ()<UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@end

@implementation LeaderPersonalInforVC
{
    UITableView *_tableView;
    NSDictionary *_responseDic;
    
    UIImageView *_iconImageView;
    
    UITextField *_nickNameTF;
    UITextField *_nameTF;
    UITextField *_ageTF;
    UITextField *_sexTF;
    UITextField *_cityTF;
    UITextField *_idCardTF;
    NSString *_imgUrl;

}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"修改资料";
    self.view.backgroundColor = superBackgroundColor;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(saveBtnAction)];
    [self initTableView];
    //去除多余的分割线
    _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
}
- (void)initTableView{
    _tableView = [[UITableView alloc]initWithFrame:self.view.frame];
    _tableView.backgroundColor = superBackgroundColor;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.scrollEnabled = NO;
    [self.view addSubview:_tableView];
}
#pragma - mrak UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 5;
    }else{
        return 1;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [[UITableViewCell alloc]init];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            cell.backgroundColor = superBackgroundColor;
            _iconImageView = [[UIImageView alloc]initWithFrame:CGRectMake(KScreenWidth/2 - 35, 10, 70, 70)];
            _iconImageView.layer.cornerRadius = 8;
            _iconImageView.layer.masksToBounds = YES;
            _iconImageView.contentMode = UIViewContentModeScaleAspectFill;
            NSString *urlStr = [NSString readToNSDefaultsWithKey:kPhotoUrl];
            [_iconImageView sd_setImageWithURL:[NSURL URLWithString:urlStr] placeholderImage:[UIImage imageNamed:@"userIcon"]];
            //imageview添加点击事件 上传头像
            _iconImageView.userInteractionEnabled = YES;
            UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(click:)];
            [_iconImageView addGestureRecognizer:singleTap];
            
            [cell.contentView addSubview:_iconImageView];
            UILabel *noticLb = [[UILabel alloc]initWithFrame:CGRectMake(0, 50, 70, 20)];
            noticLb.text = @"点击更改头像";
            [noticLb setFont:[UIFont systemFontOfSize:11]];
            noticLb.textColor = [UIColor whiteColor];
            noticLb.backgroundColor = [UIColor grayColor];
            noticLb.alpha = 0.8;
            [_iconImageView addSubview:noticLb];
        }
        if (indexPath.row == 1) {
            UILabel *nameLb = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 50, 40)];
            nameLb.font = [UIFont systemFontOfSize:15];
            nameLb.text = @"姓名";
            nameLb.textColor = Gray_Color;
            [cell.contentView addSubview:nameLb];
            _nameTF = [[UITextField alloc]initWithFrame:CGRectMake(80, 0, 200, 40)];
            _nameTF.placeholder = @"请输入姓名";
            _nameTF.text = [NSString readToNSDefaultsWithKey:kRealName];
            _nameTF.textColor = [UIColor grayColor];
            _nameTF.font = [UIFont systemFontOfSize:14];
            [cell.contentView addSubview:_nameTF];
        }
        if (indexPath.row == 2) {
            UILabel *nickNameLb = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 50, 40)];
            nickNameLb.font = [UIFont systemFontOfSize:15];
            nickNameLb.text = @"昵称";
            nickNameLb.textColor = Gray_Color;
            [cell.contentView addSubview:nickNameLb];
            _nickNameTF = [[UITextField alloc]initWithFrame:CGRectMake(80, 0, 200, 40)];
            _nickNameTF.placeholder = @"请输入昵称";
            _nickNameTF.text = [NSString readToNSDefaultsWithKey:kNickName];
            _nickNameTF.textColor = [UIColor grayColor];
            _nickNameTF.font = [UIFont systemFontOfSize:14];
            [cell.contentView addSubview:_nickNameTF];
        }
        if (indexPath.row == 3) {
            UILabel *sexLb = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 50, 40)];
            sexLb.font = [UIFont systemFontOfSize:15];
            sexLb.text = @"性别";
            sexLb.textColor = Gray_Color;
            [cell.contentView addSubview:sexLb];
            _sexTF = [[UITextField alloc]initWithFrame:CGRectMake(80, 0, 200, 40)];
            _sexTF.placeholder = @"请输入性别";
            _sexTF.text = [NSString readToNSDefaultsWithKey:kSex];
            _sexTF.textColor = [UIColor grayColor];
            _sexTF.font = [UIFont systemFontOfSize:14];
            [cell.contentView addSubview:_sexTF];
        }
        if (indexPath.row == 4) {
            UILabel *ageLb = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 50, 40)];
            ageLb.font = [UIFont systemFontOfSize:15];
            ageLb.text = @"年龄";
            ageLb.textColor = Gray_Color;
            [cell.contentView addSubview:ageLb];
            _ageTF = [[UITextField alloc]initWithFrame:CGRectMake(80, 0, 200, 40)];
            _ageTF.placeholder = @"请输入年龄";
            _ageTF.text = [NSString readToNSDefaultsWithKey:kAge];
            _ageTF.textColor = [UIColor grayColor];
            _ageTF.font = [UIFont systemFontOfSize:14];
            [cell.contentView addSubview:_ageTF];
        }
    }
    if (indexPath.section == 1) {
        UILabel *cityLb = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 50, 40)];
        cityLb.font = [UIFont systemFontOfSize:15];
        cityLb.text = @"所在地";
        cityLb.textColor = Gray_Color;
        [cell.contentView addSubview:cityLb];
        _cityTF = [[UITextField alloc]initWithFrame:CGRectMake(80, 0, 200, 40)];
        _cityTF.placeholder = @"请输入所在地";
        _cityTF.text = [NSString readToNSDefaultsWithKey:kCity];
        _cityTF.textColor = [UIColor grayColor];
        _cityTF.font = [UIFont systemFontOfSize:14];
        [cell.contentView addSubview:_cityTF];
    }
    return cell;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0 && indexPath.row == 0) {
        return 90;
    }
    return 40;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 0.01;
    }
    return 15;
}
- (void)click:(UITapGestureRecognizer *)sender{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *albumAction = [UIAlertAction actionWithTitle:@"从相册中选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //
        [self LocalPhoto];
    }];
    UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //
        [self takePhoto];
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:albumAction];
    [alert addAction:photoAction];
    [alert addAction:cancel];
    [self presentViewController:alert animated:YES completion:nil];
}
//从相册选择
-(void)LocalPhoto{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    //资源类型为图片库
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    //设置选择后的图片可被编辑
    picker.allowsEditing = YES;
    [self presentViewController:picker animated:YES completion:nil];
}
//拍照
-(void)takePhoto{
    //资源类型为照相机
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    //判断是否有相机
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]){
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        //设置拍照后的图片可被编辑
        picker.allowsEditing = YES;
        //资源类型为照相机
        picker.sourceType = sourceType;
        [self presentViewController:picker animated:YES completion:nil];
    }else {
        //        [self initBtnWithTitle:@"该设备无摄像头"];
    }
}
//取出图片
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    //1.退出图片选择器
    [picker dismissViewControllerAnimated:YES completion:nil];
    //2.取出图片
    UIImage *image = info[UIImagePickerControllerEditedImage];
    [_iconImageView setImage:image];
    NSData *dataAvatar = UIImageJPEGRepresentation(image,0.5);
    [self uploadAvatarWithImage:dataAvatar];
}
//上传头像至服务器
- (void)uploadAvatarWithImage:(NSData *)imageAvatarData{
    //参数
    NSDictionary *parameters = @{
                                 @"id":[NSString readToNSDefaultsWithKey:kId],
                                 @"imgType": @"1",
                                 };
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer=[AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager POST:@"http://115.28.152.130/tour/v1/user/imgUpload.action" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileData:imageAvatarData name:@"file" fileName:[self getImgFileName] mimeType:@"image/png"];
    } success:^(NSURLSessionDataTask *task, id responseObject) {
        
        NSDictionary *imgUrlDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"<<<<<%@",imgUrlDic);
        NSString *error = imgUrlDic[@"code"];
        if (![imgUrlDic[@"code"] isEqualToString:@"0000"]) {
            [SVProgressHUD showErrorWithStatus:[NSString errorStringWithCode:error]];
        }else{
            //请求成功
            _imgUrl = imgUrlDic[@"imgUrl"];
            //获取当前时间
            NSDate *currentDate = [NSDate date];//获取当前时间，日期
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"YYYYMMddHHmmssSSS"];
            NSString *dateString = [dateFormatter stringFromDate:currentDate];
//            NSLog(@"<<<%@",dateString);
            _imgUrl = [NSString stringWithFormat:@"%@%@%@",_imgUrl, @"?",dateString];
            NSLog(@"<<<%@",_imgUrl);
            [SVProgressHUD showSuccessWithStatus:@"上传成功"];
            
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"请检查网络问题"];
    }];
}
- (NSString *)getImgFileName {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyyMMddHHmmss";
    NSString *str = [formatter stringFromDate:[NSDate date]];
    NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
    return fileName;
}
//
- (void)saveBtnAction{
    
    NSMutableDictionary *parameters = [[NSMutableDictionary alloc]init];
    [parameters setValue:[NSString readToNSDefaultsWithKey:kId] forKey:@"id"];
    [parameters setValue:_nickNameTF.text forKey:@"nickName"];
    [parameters setValue:_nameTF.text forKey:@"realName"];
    [parameters setValue:_sexTF.text forKey:@"sex"];
    [parameters setValue:_ageTF.text forKey:@"age"];
    [parameters setValue:_cityTF.text forKey:@"city"];
    [parameters setValue:_imgUrl forKey:@"photo"];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer=[AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager POST:@"http://115.28.152.130/tour/v1/user/editUser.action" parameters:parameters success:^(NSURLSessionDataTask *operation, id responseObject) {
        _responseDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@>>>>",_responseDic);
        NSString *error = _responseDic[@"code"];
        if (![_responseDic[@"code"] isEqualToString:@"0000"]) {
            [SVProgressHUD showErrorWithStatus:[NSString errorStringWithCode:error]];
        }
        if ([_responseDic[@"code"] isEqualToString:@"3004"]) {
            [SVProgressHUD showErrorWithStatus:@"请填写年龄"];
        }else{
            //请求成功
            [SVProgressHUD showSuccessWithStatus:@"请求成功"];
            [_responseDic[@"object"][@"photo"] saveToNSDefaultsWithKey:kPhotoUrl];
            NSNumber *age = _responseDic[@"object"][@"age"];
            NSString *ageStr = age.stringValue;
            [ageStr saveToNSDefaultsWithKey:kAge];
            //                [_responseDic[@"object"][@"card"] saveToNSDefaultsWithKey:kCard];
            [_responseDic[@"object"][@"city"] saveToNSDefaultsWithKey:kCity];
            [_responseDic[@"object"][@"nickName"] saveToNSDefaultsWithKey:kNickName];
            [_responseDic[@"object"][@"sex"] saveToNSDefaultsWithKey:kSex];
            [_responseDic[@"object"][@"realName"] saveToNSDefaultsWithKey:kRealName];
            
        }
        
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"请求失败"];
    }];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
